package com.hc.core.util.verificationCode;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class VerificationCodeServlet extends HttpServlet{

	// Process the HTTP Get request
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("image/jpeg"); // 必须设置ContentType为image/jpeg
		int length = 4; // 设置默认生成4个数字
		
		Date d = new Date();
		long lseed = d.getTime();
		java.util.Random r = new Random(lseed); // 设置随机种子
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < length; i++) {
			str.append(r.nextInt(9)); // 生成随机数字
		}

		// 创建内存图像
		BufferedImage bi = new BufferedImage(40, 16, BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		g.clearRect(0, 0, 16, 40);
		g.setColor(Color.WHITE);
		g.drawString(str.toString(), 4, 12);

		try {
			// 使用JPEG编码，输出到response的输出流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
			param.setQuality(1.0f, false);
			encoder.setJPEGEncodeParam(param);
			encoder.encode(bi);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
		//保存验证码
		request.getSession().setAttribute("imagenumber", str.toString());		
	}
}
